import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/pages/Login.vue'
import HelloWorld from '@/components/HelloWorld.vue'
import HomePage from '@/pages/HomePage.vue'
import QuestionnaireEditor from '@/pages/questionnaire/QuestionnaireEditor.vue'
import QuestionnaireList from '@/pages/questionnaire/QuestionnaireList.vue'
import QuestionnairePreview from '@/pages/questionnaire/QuestionnairePreview.vue'
import QuestionnairePublish from '@/pages/questionnaire/QuestionnairePublish.vue'
import GenerateQA from '@/pages/questionnaire/GenerateQA.vue'
import WriteAnswer from '@/pages/answer/WriteAnswer.vue'
import QuestionnaireAnalysis from '@/pages/questionnaire/QuestionnaireAnalysis.vue'
import User from '@/pages/user/User.vue'
import ChangePassword from '@/pages/user/ChangePassword.vue'
import Permission from '@/pages/user/Permission.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login,
  },
  {
    path: '/HomePage',
    name: 'HomePage',
    component: HomePage,
    children: [
      {
        path: 'QuestionnaireEditor/:id',
        name: 'QuestionnaireEditor',
        component: QuestionnaireEditor
      },
      {
        path: 'QuestionnaireList',
        name: 'QuestionnaireList',
        component: QuestionnaireList
      },
      {
        path: 'QuestionnairePreview/:id',
        name: 'QuestionnairePreview',
        component: QuestionnairePreview
      },
      {
        path: 'QuestionnairePublish/:id',
        name: 'QuestionnairePublish',
        component: QuestionnairePublish
      },
      {
        path: 'GenerateQA/:id',
        name: 'GenerateQA',
        component: GenerateQA
      },
      {
        path: 'QuestionnaireAnalysis/:id',
        name: 'QuestionnaireAnalysis',
        component: QuestionnaireAnalysis
      },
      {
        path: 'User',
        name: 'User',
        component: User
      },
      {
        path: 'ChangePassword',
        name: 'ChangePassword',
        component: ChangePassword
      },
      {
        path: 'Permission',
        name: 'Permission',
        component: Permission
      }
    ]
  },
  {
        path: '/WriteAnswer/:id',
        name: 'WriteAnswer',
        component: WriteAnswer
  },
  {
    path: '/Hello',
    name: 'Hello',
    component: HelloWorld
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  // ✅ 明确白名单：登录页 + 问卷填写页
  const whiteList = ['/', '/WriteAnswer']

  // ✅ 检查当前路径是否以白名单路径开头
  const isWhiteListed = whiteList.some(path => to.path === path || to.path.startsWith(path + '/'))

  if (isWhiteListed) {
    next()
    return
  }

  if (!token) {
    next('/')
  } else {
    next()
  }
})


export default router
